<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" width="50%" draggable :fullscreen="fullscreen" :show-close="false">
    <template #header="{ titleId, titleClass, close }">
      <div class="my-header">
        <h1 :id="titleId" :class="titleClass" style="margin: 0">{{ title }}</h1>
        <div style="position: relative">
          <el-button :icon="FullScreen" @click="fullscreen = !fullscreen" circle size="small"></el-button>
          <el-button :icon="Close" @click="close" circle size="small"></el-button>
        </div>
      </div>
    </template>

    <el-dialog v-model="previewRichTextDialog" width="40%" title="预览" append-to-body>
      <div class="view" v-html="previewRichTextContent"></div>
    </el-dialog>

    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" :disabled="preview">
      <el-form-item
        :label="item.dimensionExtra == DimensionExtraEnum.dimension_primary_key ? `主键-${item.columnCode}` : item.columnName"
        :prop="item.columnCode"
        v-for="item in columnList"
        :key="item.columnCode"
      >
        <el-date-picker
          v-if="item.columnType == ColumnTypeEnum.date"
          v-model="ruleForm[item.columnCode]"
          :type="item.dimensionExtra"
          unlink-panels
          :value-format="DatePickerFormat[item.dimensionExtra!]"
          start-placeholder="开始日期"
          range-separator="-"
          end-placeholder="结束日期"
        />

        <el-input
          type="number"
          v-else-if="
            item.columnType == ColumnTypeEnum.number && getColumnOptionsType(item.columnOptions) == ColumnOptionsType.null
          "
          v-model="ruleForm[item.columnCode]"
          :disabled="item.dimensionExtra == DimensionExtraEnum.dimension_primary_key"
        />

        <!--文件-->
        <div
          class="block"
          v-else-if="
            item.dimensionExtra == DimensionExtraEnum.indicators_image ||
            item.dimensionExtra == DimensionExtraEnum.indicators_file
          "
        >
          <UploadImgs
            v-model:file-list="ruleForm[item.columnCode]"
            height="140px"
            width="140px"
            :file-size="5"
            :api="
              item.dimensionExtra == DimensionExtraEnum.indicators_image
                ? fileDetailController.uploadImageUsingPOST
                : fileDetailController.uploadUsingPOST
            "
          >
            <template #empty>
              <el-icon>
                <Picture />
              </el-icon>
              <span>请上传</span>
            </template>
            <template #tip> 大小不能超过 5M</template>
          </UploadImgs>
        </div>
        <SelectFormItem
          v-else-if="getColumnOptionsType(item.columnOptions) != ColumnOptionsType.null"
          :column-options="item.columnOptions"
          v-model:value="ruleForm[item.columnCode]"
        ></SelectFormItem>
        <el-input
          v-else-if="item.dimensionExtra == DimensionExtraEnum.indicators_password"
          :type="item.dimensionExtra"
          show-password
          v-model="ruleForm[item.columnCode]"
        />
        <el-input
          v-else-if="item.dimensionType == DimensionTypeEnum.dimension"
          v-model="ruleForm[item.columnCode]"
          :disabled="item.dimensionExtra == DimensionExtraEnum.dimension_primary_key"
        />

        <WangEditor
          v-else-if="item.dimensionExtra == DimensionExtraEnum.indicators_richText"
          v-model:value="ruleForm[item.columnCode]"
          height="400px"
        />

        <el-input
          v-else
          :type="item.dimensionExtra"
          v-model="ruleForm[item.columnCode]"
          :disabled="item.dimensionExtra == DimensionExtraEnum.dimension_primary_key"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"> 确认</el-button>
        <el-button @click="resetForm(ruleFormRef)"> 重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts" name="AddDataDialog">
import { computed, provide, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { API } from "@/api/modules/dwh/typings";
import { Close, FullScreen, Picture } from "@element-plus/icons-vue";
import { ColumnOptionsType, ColumnTypeEnum, DatePickerFormat, DimensionExtraEnum, DimensionTypeEnum } from "@/utils/dict";
import UploadImgs from "@/components/Upload/Imgs.vue";
import { fileDetailController, simpleUserTableDataController } from "@/api/modules/dwh";
import dayjs, { ManipulateType } from "dayjs";
import WangEditor from "@/components/WangEditor/index.vue";
import SelectFormItem from "@/components/SearchForm/components/SelectFormItem.vue";
import { getColumnOptionsType } from "@/utils/TableColumnUtil";
import md5 from "md5";

const fullscreen = ref<boolean>(false);
const previewRichTextDialog = ref<boolean>(false);
const previewRichTextContent = ref<string>("");

provide("previewRichText", (content: string) => {
  previewRichTextContent.value = content;
  previewRichTextDialog.value = true;
});

const handleCommand = (command: string | number | object) => {
  ElMessage(`click on item ${command}`);
};
// dialog状态
const dialogVisible = ref(false);

const props = defineProps<{
  columns: Array<API.TableColumnVo>;
  title?: string;
  tableInfoId?: number | string;
  primaryKey?: string;
}>();

const preview = ref(true);

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<{ [key: string]: any }>({});

const columnList = computed(() => {
  return props.columns.filter(
    item => item.dimensionType[0] != DimensionTypeEnum.agg && item.dimensionType != DimensionTypeEnum.agg
  );
});

const rules = reactive<FormRules>({
  // name: [
  //   { required: true, message: "Please input Activity name", trigger: "blur" },
  //   { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" }
  // ],
  // phone: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  // region: [
  //   {
  //     required: true,
  //     message: "Please select Activity zone",
  //     trigger: "change"
  //   }
  // ],
  // date1: [
  //   {
  //     type: "date",
  //     required: true,
  //     message: "Please pick a date",
  //     trigger: "change"
  //   }
  // ],
  // date2: [
  //   {
  //     type: "date",
  //     required: true,
  //     message: "Please pick a time",
  //     trigger: "change"
  //   }
  // ],
  // resource: [
  //   {
  //     required: true,
  //     message: "Please select activity resource",
  //     trigger: "change"
  //   }
  // ],
  // desc: [{ required: true, message: "Please input activity form", trigger: "blur" }]
});
const emit = defineEmits<{
  submitCallback: [value: boolean];
}>();

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let columnValueParams: API.ColumnValueParam[] = Object.keys(ruleForm).map(code => {
        return {
          columnCode: code,
          value: ruleForm.dimensionExtra == DimensionExtraEnum.indicators_password ? md5(ruleForm[code]) : ruleForm[code]
        };
      });
      let whereColumnValueParams = [];
      if (ruleForm[props.primaryKey!]) {
        whereColumnValueParams.push({
          columnCode: props.primaryKey,
          value: ruleForm[props.primaryKey!]
        });
      }

      await simpleUserTableDataController.saveUserTableDataUsingPOST({
        tableInfoId: props.tableInfoId!,
        columnValueParams: columnValueParams,
        whereColumnValueParams: whereColumnValueParams
      });
      dialogVisible.value = false;
      emit("submitCallback", true);
      ElMessage.success("成功 : ");
    } else {
      emit("submitCallback", false);
      ElMessage.error("校验错误");
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const initValue = () => {
  props.columns.forEach(col => {
    if (col.defaultValue) {
      if (col.columnType == ColumnTypeEnum.date) {
        let values = col.defaultValue.split("_");
        let startDate = dayjs()
          .subtract(Number(values[0]), values[1] as ManipulateType)
          .format(DatePickerFormat[col.dimensionExtra]);

        if (col.dimensionExtra.includes("range")) {
          ruleForm[col.columnCode] = [startDate, dayjs().format(DatePickerFormat[col.dimensionExtra])];
        } else {
          ruleForm[col.columnCode] = startDate;
        }
      } else {
        ruleForm[col.columnCode] = col.defaultValue;
      }
    }
  });
};

const show = (row?: { [key: string]: any }, previewed?: boolean) => {
  Object.keys(ruleForm).forEach(key => {
    delete ruleForm[key];
  });
  if (previewed != undefined) {
    preview.value = previewed;
  }
  if (row) {
    Object.assign(ruleForm, row);
  } else {
    initValue();
  }
  dialogVisible.value = true;
};

defineExpose({
  show
});
</script>

<style scoped lang="scss">
@import "./index.scss";

.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
